#!/usr/bin/env python3
# -*- coding:utf-8 -*-

import socket
from multiprocessing.dummy import Pool


class HeaDer:
    global http_header
    http_header = []
    _client = ''

    def __init__(self, ip: str, ports: list):
        self.ip = ip
        self.ports = ports

    def run_sock(self):
        """
        多线程跑GET请求
        :return:
        """
        pool = Pool(10)
        for port in self.ports:
            pool.apply_async(self.sock, (int(port),))
        pool.close()
        pool.join()
        return iter(http_header)

    def sock(self, port: int):
        """
        构造GET请求判断响应包中banner信息
        :param port:
        :return:
        """
        try:
            socket.setdefaulttimeout(3)
            client_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            client_sock.connect((self.ip, port))
            client_sock.send("GET / HTTP/1.1\r\n\r\nHost: {0}:{1}\r\nConnection: close\r\n\r\n".format(self.ip, port).encode('utf-8'))
            respons = client_sock.recv(4096).decode('utf-8')
            http_header.append((port, respons))
        except Exception:
            pass
        finally:
            client_sock.close()





